package com.wyhello.tube4.spring.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.File; 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.wyhello.tube4.pojo.Bag;
import com.wyhello.tube4.pojo.Dictionary;
import com.wyhello.tube4.pojo.Draw;
import com.wyhello.tube4.pojo.Macroscopic;
import com.wyhello.tube4.pojo.Position;
import com.wyhello.tube4.pojo.Reality;
import com.wyhello.tube4.pojo.Reside;
import com.wyhello.tube4.pojo.Tube;
import com.wyhello.tube4.pojo.Working;
import com.wyhello.tube4.spring.model.BagRecordsModel;
import com.wyhello.tube4.spring.model.MeterRecordsModel;
import com.wyhello.tube4.spring.model.ResideRecordsModel;
import com.wyhello.tube4.spring.model.WorkingRecordsModel;
import com.wyhello.tube4.util.DateUtil;
import com.wyhello.tube4.util.Rule;

@Controller
public class MeterRecordController {

	@Autowired
	private MeterRecordsModel meterRecordsModel;
	
	@Autowired
	private ResideRecordsModel resideRecordsModel;
	
	@Autowired
	private WorkingRecordsModel workingRecordsModel;
	
	@Autowired
	private BagRecordsModel bagRecordsModel;
	
	/**
	 * 查询测量记录
	 * 包括实际与宏观
	 * @return
	 */
	@RequestMapping("/macroscopic/query")
	public ModelAndView query(){
		List<Reside> boilers =  meterRecordsModel.queryResideByBoiler();
		for (Reside reside : boilers) {
			reside.setDescription(Boolean.toString(workingRecordsModel.queryNoWorkingEndByResideId(reside.getId())));
		}
		ModelAndView model = new ModelAndView("main","boilers",boilers);
		return model;
	}
	/**
	 * 添加实际测量信息
	 * @param reality
	 * @param positionId
	 * @return
	 */
	@RequestMapping("/macroscopic/saveReality")
	public String saveReality(Reality reality, Macroscopic macroscopic, String strtime, int positionID, String worker){
		
		Position position = resideRecordsModel.getPositionById(positionID);
		Bag bag = bagRecordsModel.getBagById(bagRecordsModel.queryBagMaxId(position.getTube().getReside().getReside().getReside().getId()));
		
		if(reality.getOuterDiameterX() > 0 && reality.getOuterDiameterY() >0 && reality.getWallThick() >0){
			//外径和壁厚全部测量时才保存数据
			//保存实际测量记录
			reality.setWorker(worker);
			reality.setTime(DateUtil.str2Date(strtime, null));
			reality.setPosition(position);
			
			List<Working> list = workingRecordsModel.queryWorkingEndByResideId(position.getTube().getReside().getReside().getReside().getId()); 
			float totalTime = 0;
			for (Working w : list) {
				totalTime += w.getUseTime();
			}
			Working working = list.get(0);
			reality.setRuntime(working.getUseTime());
			//计算蠕胀值
			//System.out.println(reality.getOuterDiameterX()+"aaaaaaaaaaaa");
			if(reality.getOuterDiameterX() == 0){
				reality.setCreepValueX(0);
			}else{
				float creepValueX = Rule.calculateCreep(reality.getOuterDiameterX(), position.getOuterDiameter());
				reality.setCreepValueX(creepValueX);
			}
			if(reality.getOuterDiameterY() == 0){
				reality.setCreepValueY(0);
			}else{
				float creepValueY = Rule.calculateCreep(reality.getOuterDiameterY(), position.getOuterDiameter());
				//reality.setCreepValueX(creepValueY);
				reality.setCreepValueY(creepValueY);
			}
			//计算磨损速率
			float wearRate = 0;
			if(reality.getWallThick() == 0){
				reality.setWearRate(0);
			}else{
				if(position.getRealitys().size() == 0){
					wearRate = Rule.calculateAbrade(position.getWallThick(), reality.getWallThick(), reality.getRuntime()); 
				}else{
					int id = meterRecordsModel.queryRealityMaxId(positionID);
					Reality last = meterRecordsModel.getRealityById(id);
					wearRate = Rule.calculateAbrade(last.getWallThick(), reality.getWallThick(), reality.getRuntime());
				}
				if(wearRate > 0){
					reality.setWearRate(wearRate);
				}else{
					reality.setWearRate(0);
				}
			}
			//估算寿命
			float lifetime = 0;
			if(wearRate > 0){
				lifetime = Rule.calculateLife(reality.getWallThick(), position.getWallLimitValue(), wearRate);
			}else{
				lifetime = 240 - totalTime;
			}
			reality.setLifetime(lifetime);
			reality.setBag(bag);
			//保存
			meterRecordsModel.saveReality(reality);
			
		}
		
		System.out.println(macroscopic);
		
		if(macroscopic.getWash() != null || macroscopic.getAbrade() != null
				|| macroscopic.getSuperheat() != null || macroscopic.getCorrode() != null
				|| macroscopic.getTransformation() != null || !"".equals(macroscopic.getDescription())){
			
			if(macroscopic.getWash() == null) macroscopic.setWash(false);
			if(macroscopic.getAbrade() == null) macroscopic.setAbrade(false);
			if(macroscopic.getSuperheat() == null) macroscopic.setSuperheat(false);
			if(macroscopic.getCorrode() == null) macroscopic.setCorrode(false);
			if(macroscopic.getTransformation() == null) macroscopic.setTransformation(false);
			
			//保存宏观测量记录
			macroscopic.setWorker(worker);
			macroscopic.setTime(DateUtil.str2Date(strtime, null));
			macroscopic.setPosition(position);
			macroscopic.setBag(bag);
			meterRecordsModel.saveMacroscopic(macroscopic);
		}
		
		
		return "realitySuccess";
	}
	/**
	 * 添加宏观测量信息
	 * @param macroscopic
	 * @param positionId
	 * @return
	 */
	/*@RequestMapping("/macroscopic/saveMacros")
	public String saveMacros(HttpServletRequest request,Macroscopic macroscopic,String strtime ,int positionID,Model model){
		macroscopic.setTime(DateUtil.str2Date(strtime, null));
		Position position = resideRecordsModel.getPositionById(positionID);
		附件上传部分
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile myfile = multipartRequest.getFile("myfile");
		if(myfile != null){
			Draw draw = null;
			String realPath = request.getSession().getServletContext().getRealPath("upload"); 
			try {
				InputStream input = myfile.getInputStream();   
				FileOutputStream fs=new FileOutputStream(realPath + "/"+ myfile.getOriginalFilename());    
				byte[] buffer =new byte[1024*1024];    
				int bytesum = 0;    
				int byteread = 0;     
				while ((byteread=input.read(buffer))!=-1){    
					  bytesum+=byteread;    
					  fs.write(buffer,0,byteread);    
					  fs.flush();    
				}     
				fs.close();    
				input.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			draw = new Draw();
			draw.setName(myfile.getOriginalFilename());
			draw.setDescription(realPath);
			macroscopic.setDraw(draw);
		}
		macroscopic.setPosition(position);
		meterRecordsModel.saveMacroscopic(macroscopic);
		return "success";
	}*/
	@RequestMapping("/macroscopic/saveMacros")
	public String saveMacros(Macroscopic macroscopic,HttpServletRequest request){
		String strtime = request.getParameter("strtime");
		String worker = request.getParameter("worker");
		String positionID = request.getParameter("positionID");
		macroscopic.setTime(DateUtil.str2Date(strtime, null));
		macroscopic.setWorker(worker);
		Position position = resideRecordsModel.getPositionById(Integer.parseInt(positionID));
		macroscopic.setPosition(position);
		Bag bag = bagRecordsModel.getBagById(bagRecordsModel.queryBagMaxId(position.getTube().getReside().getReside().getReside().getId()));
		macroscopic.setBag(bag);
		meterRecordsModel.saveMacroscopic(macroscopic);
		return "success";
	}
	/**
	 * 批量删除实际测量
	 * @param request
	 * @return
	 */
	@RequestMapping("/macroscopic/deleteReality")
	public String deleteReality(HttpServletRequest request,String url){
		String ids = request.getParameter("deletid");
		meterRecordsModel.deleteReality("("+ids+")");
		return url;
	}	
	/**
	 * 批量删除宏观测量
	 * @param request
	 * @return
	 */
	@RequestMapping("/macroscopic/deleteMacros")
	public String deleteMacros(HttpServletRequest request,String url){
		String ids = request.getParameter("deletid");
		/*删除图片信息*/
		String[] id = ids.split(",");
		for(String macroId:id){
			Macroscopic macros = meterRecordsModel.getrMacroscopic(Integer.parseInt(macroId));
			if(macros.getDraw() != null){
				String sid = String.valueOf(macros.getDraw().getId());
				Draw draw = resideRecordsModel.getDrawById(macros.getDraw().getId());
				String filePath = draw.getDescription();
				String name = draw.getName();
				meterRecordsModel.deleteMacroscopic("("+macroId+")");
				resideRecordsModel.deleteDraw("("+sid+")");
				File file = new File(filePath + "/" + name);
				file.delete();
			}
			meterRecordsModel.deleteMacroscopic("("+macroId+")");
		}	
		//meterRecordsModel.deleteMacroscopic("("+ids+")");
		return url;
	}
	/**
	 * 查询锅炉信息
	 * @return
	 */
	@RequestMapping("/macroscopic/queryMacros")
	public ModelAndView queryMacros(){
		List<Reside> boilers =  meterRecordsModel.queryResideByBoiler();
		List<Dictionary> dictionary = resideRecordsModel.queryDictionaryByType();
		ModelAndView model = new ModelAndView("form");
		model.addObject("boilers",boilers);
		return model;
	}
	/**
	 * 查询锅炉信息
	 * @return
	 */
	@RequestMapping("/macroscopic/queryRealitys")
	public ModelAndView queryRealitys(){
		List<Reside> boilers =  meterRecordsModel.queryResideByBoiler();
		ModelAndView model = new ModelAndView("reality");
		model.addObject("boilers",boilers);
		return model;
	}
	/**
	 * 根据ID查询宏观记录信息
	 * @return
	 */
	@RequestMapping("/macroscopic/queryMacrosByID")
	public ModelAndView queryMacrosByID(int macrosID){
		Macroscopic macroscopic = meterRecordsModel.getrMacroscopic(macrosID);
		ModelAndView model = new ModelAndView("form");
		model.addObject("macroscopic",macroscopic);
		return model;
	}
	/**
	 * 根据ID查询实际记录信息
	 * @return
	 */
	@RequestMapping("/macroscopic/queryRealityByID")
	public ModelAndView queryRealityByID(int realityID){
		Reality reality = meterRecordsModel.getRealityById(realityID);
		ModelAndView model = new ModelAndView("reality");
		model.addObject("reality",reality);
		return model;
	}
	/**
	 * 查询指定锅炉下的受热面
	 * @param parentid
	 * @return
	 */
	@RequestMapping("/macroscopic/querySurface")
	public void querySurface(int parentid,HttpServletResponse response){
		Reside reside = resideRecordsModel.getResideById(parentid);
		Set<Reside> surfaceSet = reside.getResides();
		Map<Integer,String> map = new HashMap<Integer,String>();
		for (Reside surface : surfaceSet) {
			map.put(surface.getId(), surface.getName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	/**
	 * 查询指定受热面下的管排
	 * @param parentid
	 * @return
	 */
	@RequestMapping("/macroscopic/queryRows")
	public void queryRows(int parentid,HttpServletResponse response){
		Reside reside = resideRecordsModel.getResideById(parentid);
		Set<Reside> rows = reside.getResides();
		Map<Integer,String> map = new HashMap<Integer,String>();
		for (Reside row : rows) {
			map.put(row.getId(), row.getName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	/**
	 * 查询指定管排下的管
	 * @param parentid
	 * @return
	 */
	@RequestMapping("/macroscopic/queryTube")
	public void queryRow(int parentid,HttpServletResponse response){
		Reside reside = resideRecordsModel.getResideById(parentid);
		Set<Tube> tubes = reside.getTubes();
		Map<Integer,String> map = new HashMap<Integer,String>();
		for (Tube tube : tubes) {
			map.put(tube.getId(), tube.getName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	/**
	 * 查询指定管的位置
	 * @param parentid
	 * @return
	 */
	@RequestMapping("/macroscopic/queryPosition")
	public void queryPosition(int parentid,HttpServletResponse response){
		Tube tube = resideRecordsModel.getTubeById(parentid);
		Set<Position> position = tube.getPositions();
		Map<Integer,String> map = new HashMap<Integer,String>();
		for (Position positions : position) {
			map.put(positions.getId(), positions.getPositionName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	/**
	 * 根据位置查询宏观记录信息
	 * @param pID
	 * @return
	 */
	@RequestMapping("/macroscopic/queryMacroBypID")
	public ModelAndView queryMacroBypID(int pID){
		Position position =  resideRecordsModel.getPositionById(pID);
		Set<Macroscopic> macroscopics = position.getMacroscopics();
		Set<Reality> realitys = position.getRealitys();
		ModelAndView model = new ModelAndView("doubleButton","macroscopics",macroscopics);
		model.addObject("realitys",realitys);
		return model;
    } 
	/**
	 * 根据管的id查询管的信息
	 * @param name
	 * @return
	 */
	@RequestMapping("/macroscopic/queryPosByTubeID")
	public ModelAndView queryPosByTubeID(String manage,String url){
		String[] ids = manage.split(",");
		List<Tube> tubeList = new ArrayList<Tube>();
		for(String id:ids){	
			tubeList.add(resideRecordsModel.getTubeById(Integer.parseInt(id)));
		}
		//System.out.println(url);
		ModelAndView model = new ModelAndView(url,"tubeList",tubeList);
		return model;
    } 
	/**
	 * 查看图片
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/macroscopic/getDrawById")
	public ModelAndView getDrawById(HttpServletRequest request,String id){
		Draw draw = resideRecordsModel.getDrawById(Integer.parseInt(id));
		ModelAndView model = new ModelAndView("draw","draw",draw);
		return model;
	}
	/**
	 * 查询全部宏观
	 * @return
	 */
	@RequestMapping("/macroscopic/queryMac")
	public ModelAndView queryMac(HttpServletRequest request){
		String begin = request.getParameter("begin");
		String end = request.getParameter("end");
		int offset = 0;
		try{
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		}catch(Exception ignore){
			
		}
		int macTotal = 0;
		List<Macroscopic> macroscopics = null;
		if(begin==""|begin==null&end==""|end==null){
			macTotal = meterRecordsModel.queryCountMacroscopic();
			macroscopics = meterRecordsModel.queryMacroscopic(offset);
		}else{
			macTotal = meterRecordsModel.queryCountMacTime(begin, end);
			macroscopics = meterRecordsModel.queryMacTime(offset, begin, end);
		}
		ModelAndView model = new ModelAndView("macroscopic","macroscopics",macroscopics);
		model.addObject("macTotal", macTotal);
		return model;
	}
	/**
	 * 查询全部实际测量
	 * @return
	 */
	@RequestMapping("/macroscopic/queryReal")
	public ModelAndView queryReal(HttpServletRequest request){
		String begin = request.getParameter("begin");
		String end = request.getParameter("end");
		int offset = 0;
		try{
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		}catch(Exception ignore){
			
		}
		List<Reality> realitys = null;
		int realTotal = 0;
		if(begin==""|begin==null&end==""|end==null){
			realTotal = meterRecordsModel.queryCountReality();
			realitys = meterRecordsModel.queryReality(offset);
		}else{
			realTotal = meterRecordsModel.queryCountReaTime(begin, end);
			realitys = meterRecordsModel.queryReaTime(offset, begin, end);
		}
		ModelAndView model = new ModelAndView("realityList","realitys",realitys);
		model.addObject("realTotal", realTotal);
		return model;
	}
	
	/**
	 * 根据id查询信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/macroscopic/queryResideById")
	public ModelAndView queryResideById(int id,String url, HttpServletRequest request){
		Reside reside = resideRecordsModel.getResideById(id);
		ModelAndView model = new ModelAndView(url,"reside",reside);
		//增加判断锅炉是否正在运行的参数
		request.setAttribute("isRunBoiler", Boolean.toString(workingRecordsModel.queryNoWorkingEndByResideId(id)));
		return model;
	}
	
	/**
	 * 根据管ID查询管信息
	 * @param id
	 * @param uil
	 * @return
	 */
	@RequestMapping("/macroscopic/getTubeById")
	public ModelAndView getTubeById(int id,String url){
		Tube tube = resideRecordsModel.getTubeById(id);
		ModelAndView model = new ModelAndView(url,"tube",tube);
		return model;
	}
}
